﻿using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class SVNUtils
{
	private static List<string> drives = new List<string>() { "c:","d:","e:","f:" };
	private static string svnPath = @"\Program Files\TortoiseSVN\bin\";
	private static string svnProc = @"TortoiseProc.exe";
	private static string svnProcPath = "";

	public static string SvnProcPath
	{
		get
		{
			if(string.IsNullOrEmpty(svnProcPath))
				svnProcPath = GetSvnProcPath();
			return svnProcPath;
		}
	}
	private static string s_assetsPath = "";
	private static string assetsPath
	{
		get
		{
			if(string.IsNullOrEmpty(s_assetsPath))
			{
				var dir = new DirectoryInfo(Application.dataPath);
				s_assetsPath = dir.Parent.FullName.Replace('/','\\');
			}
			return s_assetsPath;
		}
	}

	[MenuItem("Assets/SVN/更新 %&e")]
	public static void UpdateFromSVN()
	{
		var para = "/command:update /path:\"" + assetsPath + "\" /closeonend:0";
		System.Diagnostics.Process.Start(SvnProcPath,para);
	}

	[MenuItem("Assets/SVN/提交 %&r")]
	public static void CommitToSVN()
	{
		var para = "/command:commit /path:\"" + assetsPath + "\"";
		System.Diagnostics.Process.Start(SvnProcPath,para);
	}

	[MenuItem("Assets/SVN/回滚本地修改（更新时看到红色字请点我！） %&t")]
	public static void RevertFromSVN()
	{
		var para = "/command:revert /path:\"" + assetsPath + "\"";
		System.Diagnostics.Process.Start(SvnProcPath,para);
	}

	[MenuItem("Assets/SVN/更新策划数据 %&i")]
	public static void UpdateDataFromSVN()
	{
		var path = (Application.dataPath + "/Resources/data/xml").Replace('/','\\');
		var para = "/command:update /path:\"" + path + "\" /closeonend:0";
		System.Diagnostics.Process.Start(SvnProcPath,para);
	}

	[MenuItem("Assets/SVN/添加 %&u")]
	public static void AddToSVN()
	{
		if(string.IsNullOrEmpty(svnProcPath))
			svnProcPath = GetSvnProcPath();
		var path = Application.dataPath.Replace('/','\\');
		var para = "/command:add /path:\"" + path + "\"";
		System.Diagnostics.Process.Start(svnProcPath,para);
	}

	[MenuItem("Assets/SVN/清理 %&y")]
	public static void CleanUpFromSVN()
	{
		if(string.IsNullOrEmpty(svnProcPath))
			svnProcPath = GetSvnProcPath();
		var path = Application.dataPath.Replace('/','\\');
		var para = "/command:cleanup /path:\"" + path + "\"";
		System.Diagnostics.Process.Start(svnProcPath,para);
	}

	private static string GetSvnProcPath()
	{
		foreach(var item in drives)
		{
			var path = string.Concat(item,svnPath,svnProc);
			if(File.Exists(path))
				return path;
		}
		return EditorUtility.OpenFilePanel("Select TortoiseProc.exe","c:\\","exe");
	}
}